/**
 * Copyright 2014 the original author or authors. All rights reserved.
 */
package com.visionet.security.support;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.visionet.jumper.utils.StringUtils;
import com.visionet.security.base.constants.Constants;
import com.visionet.security.domain.entity.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;

/**
 * 
 *
 * @author suxiaojing
 * @date 
 * @since 0.0.1
 */
public class AuthorizationConverter {
	private static final String ROLES = "ROLES";
	private static final String PERMISSIONS = "PERMISSIONS";

	/**
	 * parse role object to string, support include role
	 * @return
	 */
	private static Map<String, Set<String>> parseRoles(Set<Role> roles) {
		Map<String, Set<String>> authMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(roles)) {
			Set<String> roleSet = new HashSet<>();
			Set<String> permissionSet = new HashSet<>();
			for (Role role : roles) {
				roleSet.add(role.getCode());
				if (CollectionUtils.isNotEmpty(role.getPrivileges())) {
					for (Privilege privilege : role.getPrivileges()) {
						Resource resource = privilege.getResource();
						String[] operations = StringUtils.split(privilege.getOperations(), ",");
						for (String operation : operations) {
							StringBuilder permissionString = new StringBuilder(resource.getDomain()).append(
									Constants.PERMISSION_SEPARATOR).append(operation);
							permissionSet.add(permissionString.toString());
						}
					}
				}
				if (CollectionUtils.isNotEmpty(role.getRoles())) {
					Map<String, Set<String>> subAuthMap = parseRoles(role.getRoles());
					roleSet.addAll(subAuthMap.get(ROLES));
					permissionSet.addAll(subAuthMap.get(PERMISSIONS));
				}
			}
			authMap.put(ROLES, roleSet);
			authMap.put(PERMISSIONS, permissionSet);
		}
		return authMap;
	}

	/**
	 * Get authorization info from user
	 * @param user
	 * @return
	 */
	public static SimpleAuthorizationInfo getAuthorizationInfo(User user) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Set<String> roleSet = null;
		Set<String> permissionSet = null;
		if(user != null) {
			Map<String, Set<String>> authMap = parseRoles(user.getRoles());
			roleSet = authMap.get(ROLES);
			permissionSet = authMap.get(PERMISSIONS);
		}
		authorizationInfo.addRoles(roleSet);
		authorizationInfo.addStringPermissions(permissionSet);
		return authorizationInfo;
	}
	
}
